package com.young.ysepay.utils;

//import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @anthor wenguoqiang
 * @date: 2019/01/16 15:44
 * @company
 * @des
 **/
@Component
public class HttpClientUtils {

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;


    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());

    }


    /**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public String doPostSendJsonGetString(String url, Map<String, Object> map, Map<String, String> headers) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {

            StringEntity s = new StringEntity(JSONUtils.beanToJson(map));
            System.out.println("json>>>>>>>>>>>>" + JSONUtils.beanToJson(map));
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType

            // 把表单放到post里
            httpPost.setEntity(s);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    public byte[] doPostSendJsonGetByte(String url, Map<String, Object> map, Map<String, String> headers) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {

            StringEntity s = new StringEntity(JSONUtils.beanToJson(map));
            System.out.println("json>>>>>>>>>>>>" + JSONUtils.beanToJson(map));
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType

            // 把表单放到post里
            httpPost.setEntity(s);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        return EntityUtils.toByteArray(response.getEntity());
    }

    /**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public String doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");

            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }


    /**
     * post 方式上传文件
     *
     * @param url
     * @param param
     * @param fileKey
     * @param file
     * @return
     */
    public String doPostUpload(String url, Map<String, String> param, String fileKey, File file) throws Exception {

        CloseableHttpResponse response = null;
        try {
            if (StringUtils.isEmpty(url) || null == param || param.isEmpty()) {
                return null;
            }
            // 创建POST请求
            HttpPost post = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity();
            // 请求参数
            for (Map.Entry<String, String> entry : param.entrySet()) {
                entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8")));
            }
            entity.addPart(fileKey, new FileBody(file));
            post.setEntity(entity);
            // 发送请求
            response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new Exception("请求失败！");
            }

            HttpEntity resEntity = response.getEntity();
            return null == resEntity ? "" : EntityUtils.toString(resEntity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception es) {
                es.printStackTrace();
            }

        }

    }


    /**
     * 不带参数post请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doPoyinShenServicest(String url) throws Exception {
        return this.doPost(url, null);
    }

    public InputStream HttpGetDownLoad(String url) {


        HttpRequest httpGet = new HttpGet(url);


        CloseableHttpResponse response = null;

        try {

            response = httpClient.execute((HttpGet) httpGet);
            HttpEntity entity = response.getEntity();
            InputStream in = null;
            if (entity != null) {
                in = entity.getContent();
               /* Long length = entity.getContentLength();
                if (length <= 0) {
                    throw new RuntimeException("文件不存在");
                }*/
                return in;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}

